package fr.obsmip.sedoo.client.ui.table;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.ui.Image;

import fr.obsmip.sedoo.shared.domain.SummaryDTO;
import fr.sedoo.commons.client.widget.table.ImagedActionCell.Delegate;

public class LockableSummaryDTOActionCell<C> extends AbstractCell<C>
{

	/**
	 * The delegate that will handle events from the cell.
	 * 
	 * @param <T>
	 *            the type that this delegate acts on
	 */

	private final SafeHtml lockedHtml;
	private final SafeHtml unlockedHtml;
	private final Delegate<C> delegate;

	/**
	 * Construct a new {@link LockableSummaryDTOActionCell}.
	 * 
	 * @param message
	 *            the message to display on the button
	 * @param delegate
	 *            the delegate that will handle events
	 */
	public LockableSummaryDTOActionCell(Delegate<C> del, Image unlocked, Image locked, String title)
	{
		super("click", "keydown");
		delegate = del;
		lockedHtml = new SafeHtmlBuilder().appendHtmlConstant("<img src=\"" + locked.getUrl() + "\" tabindex=\"-1\" class=\"nonclickable\" />").toSafeHtml();
		unlockedHtml = new SafeHtmlBuilder().appendHtmlConstant("<img src=\"" + unlocked.getUrl() + "\" tabindex=\"-1\" title=\"" + title + "\" class=\"clickable\" />").toSafeHtml();
	}

	@Override
	public void onBrowserEvent(Context context, Element parent, C value, NativeEvent event, ValueUpdater<C> valueUpdater)
	{
		super.onBrowserEvent(context, parent, value, event, valueUpdater);
		if ("click".equals(event.getType()))
		{
			EventTarget eventTarget = event.getEventTarget();
			if (!Element.is(eventTarget))
			{
				return;
			}
			if (parent.getFirstChildElement().isOrHasChild(Element.as(eventTarget)))
			{
				// Ignore clicks that occur outside of the main element.
				onEnterKeyDown(context, parent, value, event, valueUpdater);
			}
		}
	}

	@Override
	public void render(com.google.gwt.cell.client.Cell.Context context, C value, SafeHtmlBuilder sb)
	{
		SummaryDTO summary = (SummaryDTO) value;
		if (summary.isEditable() == false)
		{
			sb.append(lockedHtml);
		} else
		{
			sb.append(unlockedHtml);
		}
	}

	@Override
	protected void onEnterKeyDown(Context context, Element parent, C value, NativeEvent event, ValueUpdater<C> valueUpdater)
	{
		SummaryDTO summary = (SummaryDTO) value;
		if (summary.isEditable() == true)
		{
			delegate.execute(value);
		}
	}

}
